# coding=utf-8
# python ./generate-schema.py --help # 获取帮助
import mysql.connector
import sys
import pyperclip
import re
import argparse


# 下划线转驼峰
def underscore_to_camelcase(text, capitalize_first=True):
    parts = text.split("_")
    camelcase = "".join(word.title() for word in parts)
    camelcase = re.sub(r"\W+", "", camelcase)  # 删除非字母数字字符
    if capitalize_first:
        camelcase = camelcase[0].upper() + camelcase[1:]  # 首字母大写
    else:
        camelcase = camelcase[0].lower() + camelcase[1:]  # 首字母小写
    return camelcase


def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix) :]
    return text


# 根据列的数据类型获取属性类型
def get_property_type(column_type):
    type_mapping = {
        "int": "int",
        "float": "float",
        "string": ["string", "char", "text", "datetime", "date"],
    }

    for key, value in type_mapping.items():
        if any(substring in column_type for substring in value):
            return key

    return "mixed"


parser = argparse.ArgumentParser(
    prog="python ./generate-schema.py", description="生成模型类脚本", epilog="help"
)
parser.add_argument("-u", "--user", required=True, help="用户名")
parser.add_argument("-ho", "--host", required=True, help="数据库host")
parser.add_argument("-p", "--password", required=True, help="数据库密码")
parser.add_argument("-po", "--port", default=3306, help="数据库端口")
parser.add_argument("-d", "--database", required=True, help="数据库名")
parser.add_argument("-t", "--table", required=True, help="表名")
parser.add_argument("-o", "--output", required=False, help="输出的相对路径")
parser.add_argument("-pr", "--prefix", required=False, help="表前缀，会自动移除")
args = parser.parse_args()
# 从命令行参数中获取表格名称和输出路径
user = args.user
password = args.password
host = args.host
port = args.port
table_name = args.table
output_path = args.output
prefix = args.prefix

# 连接MySQL数据库
database = "yunmenshan"
cnx = mysql.connector.connect(
    user,
    password,
    host,
    database,
    port,
)
cursor = cnx.cursor()

result = []
try:
    # 定义SQL语句，获取表格列名、数据类型和注释
    sql = f"SELECT DISTINCT column_name, column_type, column_comment FROM information_schema.columns WHERE table_name = '{table_name}' AND TABLE_SCHEMA = '{database}'"
    # 执行SQL语句
    cursor.execute(sql)

    # 获取查询结果
    result = cursor.fetchall()

except mysql.connector.Error as err:
    print(f"Error: {err}")
    sys.exit()

finally:
    # 关闭连接
    cursor.close()
    cnx.close()

camelcase = underscore_to_camelcase(
    prefix if prefix == None else remove_prefix(table_name, prefix)
)

# 输出查询结果
out = ""
out += f"""<?php

namespace app\common\model;

use app\BaseModel;

/**
"""
for row in result:
    property_name = "$" + row[0]
    column_type = row[1].split("(")[0]  # 去除类型中的长度信息
    property_type = get_property_type(column_type)
    column_comment = row[2] if row[2] else property_name
    out += f" * @property {property_type} {property_name} {column_comment}\n"
out += (
    """ */
class """
    + camelcase
    + """ extends BaseModel
{
"""
)

out += "    protected $schema = [\n"
for row in result:
    column_name = row[0]
    column_type = row[1].split("(")[0]  # 去除类型中的长度信息
    column_comment = row[2] if row[2] else column_name
    out += f"        '{column_name}'\t => '{column_type}',\t // {column_comment}\n"
out += "    ];\n"

out += "}"

# 输出到文件
print(out)
if output_path:
    output_file_path = f"{output_path}/{camelcase}.php"
    with open(output_file_path, "w", encoding="utf-8") as file:
        file.write(out)
        print(f"已输出到{output_file_path}")

pyperclip.copy(out)
print("已写入粘贴板")
